// KULoket Printer 
// Resource: background.js
// Version: 1.0
// Author: Pieter Laenen

/*
	The KULoket Printer Extension makes the information in the KULoket webapplication printable. 
*/

chrome.tabs.onUpdated.addListener(checkUrl);

/* URL check for icon.
// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.*/
function checkUrl(tabId, info, tab) {
	if(info['status'] != 'complete'){return;}
	
	var url = tab.url;
	var protocol = url.split('//');
	protocol = protocol[1].split('/');
  
	//pageAction icon of KULoket Printer will appear in all sites starting with the given url.
	if(protocol[0] == "webwsps.aps.kuleuven.be" && protocol[1] == "irj"){ 
		chrome.tabs.executeScript(tabId,  {file: "content-script.js"});
		chrome.pageAction.show(tabId);
	}
    
};

/*
 *	Request listener
 */
chrome.extension.onRequest.addListener(getResourceURL);

/*
 * Request handler for content script
 */
function getResourceURL(request, sender, sendResponse){
	var file;
	
	if(request.page != null){
		file = "CSS/kulprinter_"+ request.page + ".css";
	}
	else if(request.override){
		file = "print_override.js";
	}
	else if(request.icon){
		file = "icon-small-14.png";
	}
	else if(request.pageIcon != null){
		
		if(request.pageIcon){
			console.log("Icon enabled");
			chrome.pageAction.setIcon({path:"icon-small.png", tabId:sender.tab.id});
			chrome.pageAction.setTitle({title:"KULoket Printer"
				, tabId:sender.tab.id});
		}
		else{
			console.log("Icon disabled");
			chrome.pageAction.setIcon({path:"icon-small-x.png", tabId:sender.tab.id});
			chrome.pageAction.setTitle({title:"Printing is not available"
				, tabId:sender.tab.id});
		}
	}
	var url = chrome.extension.getURL(file);
	sendResponse(url);
	
}